<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 封装函数：实现对数组或对象的深拷贝（多层）
      function copyDeep(target) {
        // 仅对引用类型进行拷贝
        if (typeof target !== 'object') {
          return target
        }

        // 判断是数组还是对象
        var result = Array.isArray(target) ? [] : {}

        if (Array.isArray(target)) {
          // 数组，for循环
          for (var i = 0; i < target.length; i++) {
            // 递归调用自己
            result.push(copyDeep(target[i]))
          }
        } else {
          // 对象，for-in
          for (var k in target) {
            // target[k] 可能是基本类型，也可以是引用类型（数组、对象）
            result[k] = copyDeep(target[k])
          }
        }

        return result
      }

      var obj1 = {
        name: 'wzy',
        hobby: ['写代码', '翻墙'],
        address: { area: '深圳', number: 109 },
      }
      var obj2 = copyDeep(obj1)

      obj2.name = 'szy'
      obj2.hobby.push('唱歌')

      console.log(obj1)
      console.log(obj2)
    </script>
  </body>
</html>
